<template>
  <GlobalContainer className="flex flex-col" :backgroundImage="`${OSS_URL}/images/baoxiu/head_bg.png`">
    <GlobalHeader title="订单详情" showBack :backgroundImage="`${OSS_URL}/images/baoxiu/head_bg.png`" :fixed="true" />
    <div class="mt-18 px-32 pb-150">
      <div class="specification-c !mb-20 overflow-hidden rounded-20 bg-white">
        <div class="status-c" :class="getStatusClass(orderDetail.status)">
          <div class="create-time">{{ orderDetail.createTime }}</div>
          <div class="status ml-auto">{{ statusMap[orderDetail.status] }}</div>
        </div>
        <div class="px-24 py-32">
          <div class="item-c flex items-center">
            <div class="value !ml-0 text-34 font-bold text-[#303133]">{{ orderDetail.address }}</div>
          </div>
          <div class="item-c flex items-center">
            <div class="label">{{ orderDetail.contacts }} {{ orderDetail.phone }}</div>
          </div>
          <div class="h-px mb-20 bg-[#efefef]" />
          <div class="item-c flex">
            <div class="label mb-20 !w-auto">服务时间</div>
            <div class="value">
              <div>
                最早<span class="ml-10 text-[#303133]">{{
                  orderDetail.serviceTime ? format(orderDetail.serviceTime, 'yyyy年MM月dd日 HH点') : '-'
                }}</span>
              </div>
              <div>
                最晚<span class="ml-10 text-[#303133]">{{
                  orderDetail.serviceEndTime ? format(orderDetail.serviceEndTime, 'yyyy年MM月dd日 HH点') : '-'
                }}</span>
              </div>
            </div>
          </div>
          <div class="item-c flex items-center">
            <div class="label">规格</div>
            <div class="value">{{ orderDetail.mallOrderDetailsList[0].mallSkuValue || '无' }}</div>
          </div>
        </div>
      </div>
      <div class="detail-c mb-20 rounded-20 bg-white px-32 py-24">
        <div class="cell-c">
          <div class="label font-bold text-[#303133]">{{ orderDetail.productDesc }}</div>
          <div class="content text-[#303133]">明细</div>
        </div>
        <div class="h-px mb-24 bg-[#efefef]" />

        <div v-for="item in orderDetail.mallOrderDetailsList" :key="item.id">
          <div class="cell-c">
            <div class="label">{{ item.mallSkuValue }}</div>
            <div class="content">
              <span>￥{{ item.price }}</span>
              <template v-if="item.mallSkuUnit"> / {{ item.mallSkuUnit }}</template>
            </div>
          </div>
          <div class="cell-c">
            <div class="label">数量</div>
            <div class="content">{{ item.num }}</div>
          </div>
          <div class="cell-c">
            <div class="label">合计</div>
            <div class="content text-34 font-bold !text-[#F04864]">￥{{ item.totalPrice }}</div>
          </div>
        </div>
      </div>
      <div class="remark-c mb-20 rounded-20 bg-white px-32 py-24">
        <div class="cell-c !mb-0 !items-start">
          <div class="label min-w-100 text-[#606266]">备注</div>
          <div class="content">{{ orderDetail.remarks || '无' }}</div>
        </div>
      </div>
    </div>
    <!-- // 待支付或者进行中已付款的 -->
    <div v-if="orderDetail.status === 10 || (orderDetail.status === 20 && orderDetail.payStatus === 1)" class="btn-c px-30 py-20 pb-safe">
      <template v-if="orderDetail.status === 10 && timeout > 0">
        <div class="mb-24 text-26 text-[#303133]">
          订单剩余支付：<span class="mx-8 text-[#F04864]">{{ formatTime }}</span> 请及时支付
        </div>
        <div class="div flex items-center justify-between">
          <div class="btn mr-20 border-[#CDD0D6] !bg-white !text-[#606266]" @tap="cancelHandle">取消预约</div>
          <div class="btn" @tap="payOrder">立即支付</div>
        </div>
      </template>
      <template v-if="orderDetail.status === 20 && orderDetail.payStatus === 1">
        <div class="btn" @tap="refundHandle">退款</div>
      </template>
    </div>
  </GlobalContainer>
</template>

<script setup>
import { ref, computed } from 'vue'
import { getOrderDetail, cancelOrder, applyRefund } from '@/common/api/report'
import { getBuildingListApi } from '@/common/api/base'
import { mallPayment } from '@/common/api/order'
import { showModal } from '@/utils'
import { format } from 'date-fns'

const OSS_URL = import.meta.env.VITE_OSS_URL
const orderDetail = ref({})
const roomList = ref([])

const statusMap = {
  0: '已关闭',
  10: '待支付',
  20: '进行中',
  25: '退款',
  40: '已完成',
  60: '已取消'
}
const getStatusClass = status => {
  switch (status) {
    case 10:
      return 'status-wait'
    case 20:
      return 'status-ing'
    case 40:
      return 'status-ok'
    case 60:
      return 'status-default'
    default:
      return 'status-default'
  }
}
onLoad(options => {
  console.log('[ options ] >', options.orderId)
  getRoomList()
  getOrderDetailHandle(options.orderId)
})
const getRoomList = () => {
  getBuildingListApi({}).then(res => {
    roomList.value = res
  })
}
const getOrderDetailHandle = id => {
  getOrderDetail({ id }).then(res => {
    orderDetail.value = res
    if (res.closingTime) {
      timeout.value = (new Date(res.closingTime.replace(/-/g, '/')).getTime() - new Date().getTime()) / 1000
    }
    countDown(timeout.value)
  })
}

const timeout = ref(0)
const formatTime = computed(() => {
  return `${Math.floor(timeout.value / 60)}:${parseInt(timeout.value % 60)}`
})
const countDown = () => {
  function countDownHandle() {
    setTimeout(() => {
      if (timeout.value < 1) {
        return
      } else {
        countDownHandle()
        timeout.value = --timeout.value
      }
    }, 1000)
  }
  countDownHandle()
}
const cancelHandle = () => {
  cancelOrder({ id: orderDetail.value.id }).then(res => {
    if (res) {
      getOrderDetailHandle(orderDetail.value.id)
    }
  })
}

const refundHandle = id => {
  showModal({
    title: '提示',
    content: '确定申请退款吗？',
    confirmText: '确定',
    cancelText: '取消',
    success: () => {
      uni.showLoading({
        title: '处理中'
      })
      applyRefund({ id: orderDetail.value.id })
        .then(res => {
          getPageHandle(statusBarActive.value)
        })
        .finally(() => {
          uni.hideLoading()
        })
    },
    cancel: () => {}
  })
}

const payOrder = () => {
  uni.showLoading({
    title: '支付中'
  })
  mallPayment({ mallOrderNo: orderDetail.value.orderNo }).then(res => {
    const { prepayId, nonceStr, timeStamp, paySign } = res
    uni.requestPayment({
      provider: 'wxpay',
      timeStamp: String(timeStamp),
      nonceStr: nonceStr,
      package: 'prepay_id=' + prepayId,
      signType: 'SHA256withRSA',
      paySign: paySign,
      orderInfo: {
        appId: '',
        timeStamp: String(timeStamp),
        nonceStr: nonceStr,
        package: ''
      },
      success: res => {
        console.log('[ res ] >', res)
        uni.switchTab({
          url: '/pages/home/index'
        })
      },
      complete: () => {
        uni.hideLoading()
        getOrderDetailHandle(orderDetail.value.id)
      }
    })
  })
}
</script>
<style scoped lang="scss">
.status-c {
  padding: 32rpx 26rpx;
  display: flex;
  align-items: center;
  .create-time {
    font-weight: 400;
    font-size: 30rpx;
    color: #606266;
  }
}
.specification-c {
  width: 686rpx;
  margin: 0 auto;
  .item-c {
    padding: 8rpx 0;
    margin-bottom: 20rpx;
    line-height: 45rpx;
    .label {
      white-space: nowrap;
      font-size: 30rpx;
      font-weight: 400;
      color: #303133;
    }
    .value {
      margin-left: auto;
      font-size: 30rpx;
      color: #303133;
      margin-right: 24rpx;
    }
  }
}

.cell-c {
  margin-bottom: 24rpx;
  display: flex;
  align-items: center;
  font-weight: 400;
  line-height: 42rpx;
  font-size: 28rpx;
  .label {
    color: #606266;
  }
  .content {
    margin-left: auto;
    color: #606266;
  }
}

.remark-c {
}

.btn-c {
  position: fixed;
  bottom: 12rpx;
  left: 0;
  right: 0;
  width: 100%;
  z-index: 100;
  background: #fff;
  .btn {
    flex: 1;
    height: 94rpx;
    background: #1e90ff;
    border-radius: 10rpx 10rpx 10rpx 10rpx;
    text-align: center;
    line-height: 94rpx;
    color: #fff;
    font-size: 32rpx;
    border-width: 1px;
  }
}
.status-wait {
  color: #ff8000;
  background: linear-gradient(183deg, #fff1d6 0%, #f8fbff 100%),
    radial-gradient(130% 130% at 148% 154%, #f2a100 0%, rgba(255, 170, 0, 0) 100%);
}
.status-ing {
  color: #ff4000;
  background: linear-gradient(183deg, #ffebe0 0%, #f8fbff 100%),
    radial-gradient(130% 130% at 148% 154%, #ffaa80 0%, rgba(255, 119, 51, 0) 100%);
}
.status-ok {
  color: #00b277;
  background: linear-gradient(183deg, #e5fff2 0%, #f8fbff 100%),
    radial-gradient(130% 130% at 148% 154%, #00ffaa 0%, rgba(0, 255, 170, 0) 100%);
}
.status-default {
  color: #303133;
  background: linear-gradient(183deg, #e4e7eb 0%, #f8fbff 100%),
    radial-gradient(130% 130% at 148% 154%, #9da6a6 0%, rgba(184, 204, 204, 0) 100%);
}
</style>
